<template>
  <view class="recycle">
    <AtRadio
      :options="state.options"
      :value="state.category"
      @click="handleChangeCategory"
    />

    <AtList>
      <AtListItem
        class="bgfff mt15"
        arrow='right'
        :title='state.addressInfo.address + state.addressInfo.addressDetail'
        :note="state.addressInfo.name +  state.addressInfo.phone"
        :onClick="redirect"
      />
    </AtList>
      
    <picker class="mt15" mode='date' :value="state.appointmentTime" :start="today" @change="handleDateChange">
      <AtList>
        <AtListItem title='上门时间' :extraText="state.appointmentTime" />
      </AtList>
    </picker>
    <view class="bgfff mt15 pl30 pr30 pt20 pb20">
      <view class='pb20 c333 text-mediumx'>预约重量</view>
      <view class='weightRow'>
        <view name="" v-for="item in state.weightList" 
          :key="item.value"
          @tap="chooseWeight(item)"
          :class="state.checkedWeight == item.value ? 'box-shadow radius10 pxy20 c666 text-medium act' : 'box-shadow radius10 pxy20 c666 text-medium'">
          {{item.label}}
         </view>
      </view>
    </view>

    <view class="bgfff pb10">
      <AtListItem
        class="bgfff mt15"
        title='上传照片'
      />
      <AtImagePicker
        class="pl20 pb10"
        mode='scaleToFill'
        :count="4"
        :files="state.imageIds"
        :onChange="onChange"
        :onFail="onFail"
        :onImageClick="onImageClick"
      />
      <AtInput
        name='value1'
        :border="false"
        title='备注信息'
        type='text'
        placeholder='备注信息'
        :value="state.remark"
        :onChange="(val)=>{handleChange(val,'remark')}"
      />
    </view>
    
    <view class="pl20 pr20 pt30 pb30">
      <AtButton type='primary' @click="submit">
        立即下单
      </AtButton>
    </view>
    <myFooter />
    <!-- <AtMessage /> -->
  </view>
</template>

<script setup>
import Taro from '@tarojs/taro'
import { onMounted, reactive, getCurrentInstance,ref, computed, createApp } from 'vue'
import myFooter from "../tabBar/index.vue"
import dayjs from 'dayjs'
import './recycle.scss'

import request from "../../utils/request";

const {ctx} = getCurrentInstance()

const today = ref(dayjs().format('YYYY-MM-DD'));


Taro.onAppShow((e)=>{
  console.log("onShowwwwwwwwwwwwwwwwwwww");
});


const state = reactive({
  category: '废旧物品',
  appointmentTime: dayjs().format('YYYY-MM-DD'),
  imageIds:[],

  checkedWeight: '0-5',
  remark:"",
  addressInfo:{
     name:'',
     address:'请选择上门地址',
     addressDetail:'',
     phone:''
  },
  weightList:[
    {label:'0kg-5kg',value:'0-5'},
    {label:'5kg-20kg',value:'5-20'},
    {label:'20kg-50kg',value:'20-50'},
    {label:'大于50kg',value:'>50'},
  ],
  options:[
    { label: '废旧物品', value: '废旧物品', desc: '塑料、衣物，手机等' },
    { label: '废弃金属', value: '废弃金属', desc: '生活废铁、铜、铝，工业设备元件等' },
    { label: '纸箱纸板', value: '纸箱纸板', desc: '报纸、纸板、纸箱、快递盒等' }
  ]
})

const token = computed(()=>{
  return Taro.getStorageSync("userInfo").token
})

const handleChangeCategory = (val)=>{
  state.category = val
}

const handleDateChange = (e) => {
  state.appointmentTime = e.detail.value
}

const chooseWeight = (item)=>{
  console.log(item);
  state.checkedWeight = item.value
}
const redirect = ()=>{
  Taro.navigateTo({
    url: '/pages/address/address'
  })
}


const onChange = async (res)=>{
  console.log(res);
  let type = res.operationType
  let index = res.index
  // state.imageIds = res.files

  
  
  if (type == 'add') {
      res.files.forEach(item=>{
        if (item.imageId) {
          return
        }
        console.log(item.url);
        Taro.uploadFile({
          url:`${BASEAPI}/upload`,
          filePath: item.url,
          name:'file',
          header: {
            'content-type': 'multipart/form-data'
          },
          // formData:{
          //   pictures:'params'
          // },
          complete:res=>{
            console.log(typeof res.data);
            console.log(res);
            if (res.data) {
              let data = JSON.parse(res.data)
              state.imageIds.push({url:"http://"+data.data[0].imageUrl, imageId:data.data[0].imageId})
              ctx.$toast.success("上传成功")
            }
            
          }
        })
      })
  } else if(type == "remove"){
    ctx.$toast.success("删除成功")
    state.imageIds.splice(index,1)
    console.log(state.imageIds);
  }
  
}

const handleChange = (val,field)=>{
  state[field] = val
}

const onFail = (error)=>{
  console.log(error);
  console.log(error.errMsg == 'chooseImage:fail cancel');
  // Taro.atMessage({
  //   message: mes,
  //   type:'error'
  // })
}
const onImageClick = (index, file)=>{
  console.log(index, file)
  let urls = state.imageIds.map(el=>el.url)
  Taro.previewImage({
    current: file.url, // 当前显示图片的http链接
    urls: urls // 需要预览的图片http链接列表
  })
}

const submit = async ()=>{
  console.log('submit');
  console.log(state);
  let params = {
    category:state.category,
    addressId: state.addressInfo._id,
    appointmentTime:state.appointmentTime,
    weight: state.checkedWeight,
    imageIds:state.imageIds,
    remark: state.remark,
    status:1,
  }
  let res = await request("/order/create",'post',params)
  ctx.$toast.success(res.msg);
  setTimeout(() => {
    Taro.redirectTo({
      url: '/pages/order/order'
    })
  }, 1500);
}

const getAddressList = async ()=>{
  let res = await request("/address/getList");
  console.log(res.data);
  if (res.data) {
    state.addressInfo = res.data;  
  }
}

onMounted(()=>{
  console.log(Taro.getCurrentInstance().router);
  let cateType = Taro.getCurrentInstance().router.params.cate;
  switch (Number(cateType)) {
    case 1:
      state.category = "废旧物品"
      break;
    case 2:
      state.category = "纸箱纸板"
      break;
    case 3: 
      state.category = "废旧物品"
      break;
  
    default:
      state.category = "废弃金属"
      break;
  }
   token.value && getAddressList()
});





</script>
